<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
//引入模型
use App\Admin\Stream;
use Input;
use GuzzleHttp\Client;
class StreamController extends Controller
{
    //列表
    public function index(){
    	//获取数据
    	$data = Stream::all();
    	//展示视图
    	return view('admin.stream.index',compact('data'));
    }

    //添加
    public function add(){
    	//判断请求类型
    	if(Input::method() == 'POST'){
    		//1、获取提交的数据
    		$data = Input::except('_token');
    		//2、生成QiniuToken值
    		//定义变量
    		$method = 'POST';	//请求类型
    		$path = '/v2/hubs/education-zet/streams';	//请求path，需要替换其中的hub
    		$host = 'pili.qiniuapi.com';	//host地址
    		$contentType = 'application/json';	//请求数据类型
    		$body = json_encode(['key' => $data['stream_name']]);	//请求体
    		//调用之前七牛上传SDK的签名方法，构造时候传递ak和sk
    		$qiniu = new \Qiniu\Auth('bBOpNSfGr5G1b0IFDvF68L7Za35-PAVUliL4Zrkn','AOlw43W9NjgzmNNAEoZrO1sMU5w6CGwn-7pyOekM');
    		$token = 'Qiniu ' . $qiniu -> sign("$method $path\nHost: $host\nContent-Type: $contentType\n\n$body");
    		//3、建立请求
    		$client = new Client([
			    //base_uri是用于建立相对的请求（带协议）
			    'base_uri' => 'http://' . $host
			]);
			//发送请求
			$response = $client -> post($path,[
				'headers'	=>	[
						'Authorization'	=>	$token,	//token信息
						'Content-Type'	=>	$contentType,//请求类型
				],
				'body'		=>	$body
			]);
			//4、根据状态码决定是否写入数据表
			if($response -> getStatusCode() == '200'){
				//写入数据表
				$data['permited_at'] = !$data['permited_at'] ? '0' : $data['permited_at'];
				$rst = Stream::insert($data);
				return $rst ? '1' : '0';
			}else{
				return '0';
			}
    	}else{
    		//展示视图
    		return view('admin.stream.add');
    	}
    }
}
